package o2o.web.actions.print;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.JYMathDoubleUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.print.PrintMessageMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.print.PrintMessage;
import o2o.dao.PO.sys.SysCustomerInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.order.OrderInfoVO;
import o2o.dao.VO.order.PrintOrderVO;
import o2o.dao.VO.print.PrintMessageVO;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.user.User;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pay.weixin.utils.MD5Util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class PrintMessAction {


    @RequestMapping(method = RequestMethod.POST, value = "/system/print/message")
    @ResponseBody
    public String printAction(String orderNo, String no, String printNo) {     //  订单号   打印联数
        List<PrintMessage> printMessageList = getPrintFromOrder();
        String[] print = printNo.split(",");
        for (int i = 0; i < printMessageList.size(); i++) {
            boolean flag = true;
            for (String s : print) {
                if (s.equals(String.valueOf(printMessageList.get(i).getId()))) {
                    flag = false;
                }
            }
            if (flag) {
                printMessageList.remove(i);
                i--;
            }
        }

        if (printMessageList.size() == 0) {
            return AjaxResult.errorResult("您还没有绑定可用的打印机");
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<PrintOrderVO> printOrderVOList = getOrderFromOrderNo(orderNo);

        StringBuffer sb = new StringBuffer();  //  封装信息
        if (ValidateUtil.isAbsList(printMessageList)) {
            sb.append("<MN>").append(no).append("</MN>");   // 打印多联
            sb.append("@@2点菜清单_订单编号: ").append(printOrderVOList.get(0).getOrderNo()).append("\r");
            sb.append("店名: ").append(printOrderVOList.get(0).getShopName()).append("\r");
            sb.append("联系人: ").append(printOrderVOList.get(0).getBuyer()).append("\r");
            sb.append("电话: ").append(printOrderVOList.get(0).getUserTelephone()).append("\r");
            sb.append("客户地址: ").append(printOrderVOList.get(0).getUserAddress()).append("\r");
            sb.append("下单时间: ").append(sdf.format(Long.valueOf(printOrderVOList.get(0).getCreatetime()))).append("\r");
            sb.append("用餐地址: ").append(printOrderVOList.get(0).getShopName()).append("\r");
            sb.append("商家电话: ").append(printOrderVOList.get(0).getShopTelephone()).append("\r");
            sb.append("----------------------\r");
            sb.append("@@2菜品明细").append("\r");

            Double zongMoney = 0.0;
            Double money = 0.0;
            for (int i = 0; i < printOrderVOList.size(); i++) {
                money = JYMathDoubleUtils.mul(printOrderVOList.get(i).getGoodsMoney(), printOrderVOList.get(i).getTotalcount());
                zongMoney = JYMathDoubleUtils.add(zongMoney, money);   // 商品金额
                sb.append(i + 1).append(". ").append(printOrderVOList.get(i).getGoodsName()).append("-").append(printOrderVOList.get(i).getGoodsMoney()).append("元*").append(printOrderVOList.get(i).getTotalcount()).append("份\r");
            }
            sb.append("----------------------\r");
            sb.append("@@2支付方式").append("\r");
            zongMoney = JYMathDoubleUtils.add(zongMoney, printOrderVOList.get(0).getDeliveryPrice());           // 配送费
            //  活动满减
            sb.append("外送费用: ").append(printOrderVOList.get(0).getDeliveryPrice()).append("元").append("\r");
            sb.append("菜品金额: ").append("总价").append(zongMoney).append("元-").append("活动满减").append(printOrderVOList.get(0).getOriginalYunFeiShop()).append("元-").append("配送满减").append(printOrderVOList.get(0).getAwardMoney()).append("元").append("\r");
            zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getAwardMoney());             //  配送满减
            zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getOriginalYunFeiShop());
            sb.append("应付金额: ").append(zongMoney).append("元\r");
            sb.append("留言: ").append(printOrderVOList.get(0).getNote()).append("\r");
        }
        String content = null;   //  urlencode
        try {
            content = URLEncoder.encode(sb.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        boolean flag = true;
        for (PrintMessage printMessage : printMessageList) {
            flag = sendContent(content, printMessage.getPartner(), printMessage.getMachine_code(), printMessage.getApikey(), printMessage.getMkey());
        }
        //  调用打印
        if (!flag) {
            return AjaxResult.errorResult("打印失败,检查打印机");
        }
        return AjaxResult.successResult("打印成功!");
//        if (ValidateUtil.isNotAbsInteger(type)) {
//            type = PRINT_TYPE.PRINT_TYPE_EYUNLIAN;
//        }
//        if (type == PRINT_TYPE.PRINT_TYPE_EYUNLIAN) {
//            return print_eyunlian_message(orderNo, no, printNo);
//        } else if (type == PRINT_TYPE.PRINT_TYPE_FE) {
//            return print_fe_message(shopId, orderNo, printNo);
//        }
//        return AjaxResult.errorResult("请选择合适的打印机");
    }

    private String print_eyunlian_message(String orderNo, String no, String printNo) {
        List<PrintMessage> printMessageList = getPrintFromOrder();
        String[] print = printNo.split(",");
        for (int i = 0; i < printMessageList.size(); i++) {
            boolean flag = true;
            for (String s : print) {
                if (s.equals(String.valueOf(printMessageList.get(i).getId()))) {
                    flag = false;
                }
            }
            if (flag) {
                printMessageList.remove(i);
                i--;
            }
        }

        if (printMessageList.size() == 0) {
            return AjaxResult.errorResult("您还没有绑定可用的打印机");
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<PrintOrderVO> printOrderVOList = getOrderFromOrderNo(orderNo);


        StringBuffer sb = new StringBuffer();  //  封装信息
        sb.append("<MN>").append(no).append("</MN>");   // 打印多联
        sb.append("@@2点菜清单_订单编号: ").append(printOrderVOList.get(0).getOrderNo()).append("\r");
        sb.append("店名: ").append(printOrderVOList.get(0).getShopName()).append("\r");
        sb.append("联系人: ").append(printOrderVOList.get(0).getBuyer()).append("\r");
        sb.append("电话: ").append(printOrderVOList.get(0).getUserTelephone()).append("\r");
        sb.append("客户地址: ").append(printOrderVOList.get(0).getUserAddress()).append("\r");
        sb.append("下单时间: ").append(sdf.format(Long.valueOf(printOrderVOList.get(0).getCreatetime()))).append("\r");
        sb.append("用餐地址: ").append(printOrderVOList.get(0).getShopName()).append("\r");
        sb.append("商家电话: ").append(printOrderVOList.get(0).getShopTelephone()).append("\r");
        sb.append("----------------------\r");
        sb.append("@@2菜品明细").append("\r");

        Double zongMoney = 0.0;
        Double money = 0.0;
        for (int i = 0; i < printOrderVOList.size(); i++) {
            money = JYMathDoubleUtils.mul(printOrderVOList.get(i).getGoodsMoney(), printOrderVOList.get(i).getTotalcount());
            zongMoney = JYMathDoubleUtils.add(zongMoney, money);   // 商品金额
            sb.append(i + 1).append(". ").append(printOrderVOList.get(i).getGoodsName()).append("-").append(printOrderVOList.get(i).getGoodsMoney()).append("元*").append(printOrderVOList.get(i).getTotalcount()).append("份\r");
        }
        sb.append("----------------------\r");
        sb.append("@@2支付方式").append("\r");
        zongMoney = JYMathDoubleUtils.add(zongMoney, printOrderVOList.get(0).getDeliveryPrice());           // 配送费
        //  活动满减
        sb.append("外送费用: ").append(printOrderVOList.get(0).getDeliveryPrice()).append("元").append("\r");
        sb.append("菜品金额: ").append("总价").append(zongMoney).append("元-").append("活动满减").append(printOrderVOList.get(0).getOriginalYunFeiShop()).append("元-").append("配送满减").append(printOrderVOList.get(0).getAwardMoney()).append("元").append("\r");
        zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getAwardMoney());             //  配送满减
        zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getOriginalYunFeiShop());
        sb.append("应付金额: ").append(zongMoney).append("元\r");
        sb.append("留言: ").append(printOrderVOList.get(0).getNote()).append("\r");

        String content = null;   //  urlencode
        try {
            content = URLEncoder.encode(sb.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        boolean flag = true;
        for (PrintMessage printMessage : printMessageList) {
            flag = sendContent(content, printMessage.getPartner(), printMessage.getMachine_code(), printMessage.getApikey(), printMessage.getMkey());
        }
        //  调用打印
        if (!flag) {
            return AjaxResult.errorResult("打印失败,检查打印机");
        }
        return AjaxResult.successResult("打印成功!");
    }

    // 飞鹅 打印
    public String print_fe_message(Long shopId, String orderNo, String printIds) {
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺id不能为空");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单编号不能为空");
        }
        List<PrintMessage> printMessageList = PrintMessageMemory.getInstance().listPrintMessageOfShopId(shopId, null);
        if (!ValidateUtil.isAbsList(printMessageList)) {
            return AjaxResult.errorResult("您还没有绑定可用的打印机");
        }

        List<PrintMessage> list = new ArrayList<>();
        for (int i = 0; i < printMessageList.size(); i++) {
            if (ValidateUtil.isNotNull(printIds)) {
                String temp[] = printIds.trim().split(",");
                for (String s : temp) {
                    if (s.equals(String.valueOf(printMessageList.get(i).getId()))) {
                        list.add(printMessageList.get(i));
                    }
                }
            } else {
                list.add(printMessageList.get(i));
            }
        }
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.errorResult("请选择打印机");
        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        List<PrintOrderVO> printOrderVOList = getOrderFromOrderNo(orderNo);
//        StringBuffer sb = new StringBuffer();  //  封装信息
////        sb.append("<C>").append(count).append("</C>");   // 打印多联
//        sb.append("@@点菜清单<BR>订单编号: ").append(printOrderVOList.get(0).getOrderNo()).append("<BR>");
//        sb.append("店名: ").append(printOrderVOList.get(0).getShopName()).append("<BR>");
//        sb.append("联系人: ").append(printOrderVOList.get(0).getBuyer()).append("<BR>");
//        sb.append("电话: ").append(printOrderVOList.get(0).getUserTelephone()).append("<BR>");
//        sb.append("客户地址: ").append(printOrderVOList.get(0).getUserAddress()).append("<BR>");
//        sb.append("下单时间: ").append(sdf.format(Long.valueOf(printOrderVOList.get(0).getCreatetime()))).append("<BR>");
//        sb.append("用餐地址: ").append(printOrderVOList.get(0).getShopName()).append("<BR>");
//        sb.append("商家电话: ").append(printOrderVOList.get(0).getShopTelephone()).append("<BR>");
//        sb.append("----------------------<BR>");
//        sb.append("@@菜品明细").append("<BR>");
//
//        Double zongMoney = 0.0;
//        Double money = 0.0;
//        for (int i = 0; i < printOrderVOList.size(); i++) {
//            money = JYMathDoubleUtils.mul(printOrderVOList.get(i).getGoodsMoney(), printOrderVOList.get(i).getTotalcount());
//            zongMoney = JYMathDoubleUtils.add(zongMoney, money);   // 商品金额
//            sb.append(i + 1).append(". ").append(printOrderVOList.get(i).getGoodsName()).append("-").append(printOrderVOList.get(i).getGoodsMoney()).append("元*").append(printOrderVOList.get(i).getTotalcount()).append("份\r");
//        }
//        sb.append("<BR>----------------------<BR>");
//        sb.append("@@@支付方式").append("<BR>");
//        zongMoney = JYMathDoubleUtils.add(zongMoney, printOrderVOList.get(0).getDeliveryPrice());           // 配送费
//        //  活动满减
//        sb.append("外送费用: ").append(printOrderVOList.get(0).getDeliveryPrice()).append("元").append("<BR>");
//        sb.append("菜品金额: ").append("总价").append(zongMoney).append("元-").append("活动满减").append(printOrderVOList.get(0).getOriginalYunFeiShop()).append("元-").append("配送满减").append(printOrderVOList.get(0).getAwardMoney()).append("元").append("\r");
//        zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getAwardMoney());             //  配送满减
//        zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getOriginalYunFeiShop());
//        sb.append("<BR>应付金额: ").append(zongMoney).append("元<BR>");
//        sb.append("留言: ").append(printOrderVOList.get(0).getNote()).append("<BR>");

//        String content = sb.toString();   //  urlencode
        OrderInfoVO orderInfoVO = OrderMan.getOrderDetail(orderNo);
        if (orderInfoVO == null) {
            return AjaxResult.errorResult("订单信息不存在");
        }
        String e_content = null;
        try {
            String sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            e_content = PrintMan.get_F_E_Content(orderInfoVO, customerInfo.getName(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean flag = true;
        for (PrintMessage printMessage : list) {
            flag = PrintMan.sendFeContent(e_content, printMessage.getFeUser(), printMessage.getFeUkey(), printMessage.getMachine_code(), printMessage.getFeTime());
        }
        //  调用打印
        if (!flag) {
            return AjaxResult.errorResult("打印失败,检查打印机");
        }
        return AjaxResult.successResult("打印成功!");
    }


    public static boolean sendContent(String content, String partner, String machine_code, String apiKey, String mkey) {
        System.out.println("content====" + content);
        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("partner", partner);
            params.put("machine_code", machine_code);
            String time = String.valueOf(System.currentTimeMillis());
            params.put("time", time);
            String sign = signRequest(params, apiKey, mkey);

            byte[] data = ("partner=" + partner + "&machine_code=" + machine_code + "&content=" + content + "&sign=" + sign + "&time=" + time).getBytes();

            URL url = new URL("http://open.10ss.net:8888");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5 * 1000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "text/html; charset=utf-8");
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));

            //获取输出流
            OutputStream outStream = conn.getOutputStream();
            //传入参数
            outStream.write(data);

            outStream.flush();
            outStream.close();


            //获取输入流
            InputStream is = conn.getInputStream();

            System.out.println(conn.getResponseCode());
            if (conn.getResponseCode() == 200) {
                int i = -1;
                byte[] b = new byte[1024];
                StringBuffer result = new StringBuffer();
                while ((i = is.read(b)) != -1) {
                    result.append(new String(b, 0, i));
                }

                String sub = result.toString();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //  获取打印机列表
    @RequestMapping(method = RequestMethod.POST, value = "/system/print/list")
    @ResponseBody
    public String getPrintList(Long shopId) {

        List<PrintMessage> printMessageList = getPrintFromShopId(shopId);
        if (printMessageList == null) {
            return AjaxResult.errorResult("您没有绑定的打印机");
        }
        return AjaxResult.successResult(printMessageList.size(), printMessageList);
    }

    // 根据shopId得到所有的打印机
    private List<PrintMessage> getPrintFromShopId(Long shopId) {
        List<PrintMessage> printMessageList = null;

        StringBuffer sb = new StringBuffer();
        sb.append("SELECT id,partner,machine_code,mkey,delflag,username,mobilePhone FROM ").append(PojoTables.PRINT_MESSAGE).append(" WHERE shopid=").append(shopId)
                .append(" AND delflag=0");

        try {
            printMessageList = (List<PrintMessage>) UserDaoSql.getInstance().list(PrintMessage.class, sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return printMessageList;
    }

    //  是否启用打印机
    @RequestMapping(method = RequestMethod.POST, value = "/system/print/delflag")
    @ResponseBody
    public String setPrint(int delflag, String machine_code) {

        toDelPrint(delflag, machine_code);

        if (0 == delflag) {
            return AjaxResult.successResult("启用成功");
        }
        return AjaxResult.successResult("停用成功");
    }

    //  设置打印机是否启用
    private void toDelPrint(int delflag, String machine_code) {

        StringBuffer sb = new StringBuffer();
        sb.append("UPDATE ").append(PojoTables.PRINT_MESSAGE).append(" SET delflag=").append(delflag).append(" WHERE machine_code=\'").append(machine_code).append("\'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    //  打印签名 Sign
    public static String signRequest(Map<String, String> params, String apiKey, String mKey) {
        Map<String, String> sortedParams = new TreeMap<String, String>();
        sortedParams.putAll(params);
        Set<Map.Entry<String, String>> paramSet = sortedParams.entrySet();
        StringBuilder query = new StringBuilder();
        query.append(apiKey);
        for (Map.Entry<String, String> param : paramSet) {
            query.append(param.getKey());
            query.append(param.getValue());
        }
        query.append(mKey);
        String encryptStr = MD5Util.MD5Encode(query.toString(), null).toUpperCase();
        return encryptStr;
    }

    //   打印机状态
    public static boolean pmRequest(String machine_code, String partner, String apiKey, String mKey) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("machine_code", machine_code);
        params.put("partner", partner);

        String sign = signRequest(params, apiKey, mKey);
        params.put("sign", sign);
        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod("http://open.10ss.net:8888/getstatus.php");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            post.addParameter(entry.getKey(), entry.getValue());
        }

        HttpMethodParams param = post.getParams();
        param.setContentCharset("UTF-8");

        try {
            httpClient.executeMethod(post);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //如果返回200，表明成功
        if (post.getStatusCode() == 200) {
            try {
                String result;
                result = post.getResponseBodyAsString();
                System.out.println(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        } else {
            System.out.println("打印失败！");
            return false;
        }

    }


    //  根据订单号找到打印机详细信息
    private List<PrintMessage> getPrintFromOrder() {
        List<PrintMessage> printMessageList = null;
        StringBuffer sb = new StringBuffer();
        /*   SELECT p.id,p.shopid,p.partner,p.machine_code,p.apikey,p.mkey FROM print_message p,order_info o WHERE o.shopid=p.shopid AND o.orderno= */
        sb.append("SELECT id,shopid,partner,machine_code,apikey,mkey FROM ").append(PojoTables.PRINT_MESSAGE)
                .append(" WHERE delflag=0");
        try {
            printMessageList = (List<PrintMessage>) UserDaoSql.getInstance().list(PrintMessage.class, sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return printMessageList;
    }

    //  根据订单号拿到详细信息
    //  根据订单号拿到详细信息
    private List<PrintOrderVO> getOrderFromOrderNo(String orderNo) {
        List<PrintOrderVO> printOrderVOList = null;
        StringBuffer sb = new StringBuffer();
        // 只需要未退款成功的即可
        /*  SELECT o.shopname,o.buyer,o.telephone AS usertelephone,o.address AS useraddress,o.createtime,o.shopaddress,o.shopphone AS shoptelephone,
            g.name AS goodsname,g.price AS goodsmoney,o.paytype,o.deliveryprice,o.note,o.originalYunFeiShop,o.awardMoney FROM order_info o,order_goods og,goods_info g
            WHERE  o.orderno=og.orderno AND og.goodsid=g.id */
        // sb.append("SELECT o.shopname,o.buyer,o.telephone AS usertelephone,o.address AS useraddress,o.createtime,o.shopaddress,o.shopphone AS shoptelephone,g.name AS goodsname,g.price AS goodsmoney,o.paytype,o.deliveryprice,o.note,o.originalYunFeiShop,o.awardMoney,o.orderno,og.totalcount  FROM ")
        sb.append("SELECT o.shopname,o.buyer,o.telephone AS usertelephone,o.address AS useraddress,o.createtime,o.shopaddress,o.shopphone AS shoptelephone,g.name AS goodsname,g.price AS goodsmoney,o.paytype,o.deliveryprice,o.note,o.originalYunFeiShop,o.awardMoney,o.orderno,IFNull((og.totalCount-og.backTotalCount),0) as  totalcount FROM ")
                .append(PojoTables.OrderInfo).append(" o,").append(PojoTables.OrderGoods).append(" og,").append(PojoTables.GoodsInfo).append(" g ")
                // .append("WHERE  o.orderno=og.orderno AND og.goodsid=g.id AND o.orderno=").append(orderNo);
                .append("WHERE  o.orderno=og.orderno AND og.goodsid=g.id AND o.orderno=").append(orderNo).append(" and (og.totalCount > og.backTotalCount)");
        try {
            printOrderVOList = (List<PrintOrderVO>) UserDaoSql.getInstance().list(PrintOrderVO.class, sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return printOrderVOList;
    }

    //  ==========================飞鹅打印机对接=========-===================================================================
    // 获取店铺打印机列表
    @RequestMapping(method = RequestMethod.POST, value = "/print/fe/list")
    @ResponseBody
    public String print_list(String token, Long shopId, Integer type) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        if (!User.hasShopAuth(user.getUserType())) {
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("你没有权限");
        }
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺id不能为空");
        }
        List<PrintMessage> list = PrintMessageMemory.getInstance().listPrintMessageOfShopId(shopId, type);
        if (ValidateUtil.isAbsList(list)) {
            List<PrintMessageVO> voList = list.stream().map(a -> a.convert2VO()).collect(Collectors.toList());
//            for (PrintMessage p : list) {
//                PrintMessageVO printMessageVO = new PrintMessageVO();
//                try {
//                    ObjectUtils.copyPropertiesExclude(p, printMessageVO);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    continue;
//                }
//                voList.add(printMessageVO);
//            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }
        return AjaxResult.successResult();
    }

//    @RequestMapping(method = RequestMethod.POST, value = "/print/fe/message")
//    @ResponseBody
//    public String print_fe__message(Long shopId, String orderNo, String printIds) {
//        if (ValidateUtil.isNotID(shopId)) {
//            return AjaxResult.errorResult("店铺id不能为空");
//        }
//        if (ValidateUtil.isNull(orderNo)) {
//            return AjaxResult.errorResult("订单编号不能为空");
//        }
//        List<PrintMessage> printMessageList = PrintMessageMemory.getInstance().listPrintMessageOfShopId(shopId, null);
//        if (!ValidateUtil.isAbsList(printMessageList)) {
//            return AjaxResult.errorResult("您还没有绑定可用的打印机");
//        }
//
//        List<PrintMessage> list = new ArrayList<>();
//        for (int i = 0; i < printMessageList.size(); i++) {
//            if (ValidateUtil.isNotNull(printIds)) {
//                String temp[] = printIds.trim().split(",");
//                for (String s : temp) {
//                    if (s.equals(String.valueOf(printMessageList.get(i).getId()))) {
//                        list.add(printMessageList.get(i));
//                    }
//                }
//            } else {
//                list.add(printMessageList.get(i));
//            }
//        }
//        if (!ValidateUtil.isAbsList(list)) {
//            return AjaxResult.errorResult("请选择打印机");
//        }
////        if (ValidateUtil.isNotAbsInteger(count)) {
////            count = 1;
////        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        List<PrintOrderVO> printOrderVOList = getOrderFromOrderNo(orderNo);
//        StringBuffer sb = new StringBuffer();  //  封装信息
////        sb.append("<C>").append(count).append("</C>");   // 打印多联
//        sb.append("@@2点菜清单_订单编号: ").append(printOrderVOList.get(0).getOrderNo()).append("<BR>");
//        sb.append("店名: ").append(printOrderVOList.get(0).getShopName()).append("<BR>");
//        sb.append("联系人: ").append(printOrderVOList.get(0).getBuyer()).append("<BR>");
//        sb.append("电话: ").append(printOrderVOList.get(0).getUserTelephone()).append("<BR>");
//        sb.append("客户地址: ").append(printOrderVOList.get(0).getUserAddress()).append("<BR>");
//        sb.append("下单时间: ").append(sdf.format(Long.valueOf(printOrderVOList.get(0).getCreatetime()))).append("<BR>");
//        sb.append("用餐地址: ").append(printOrderVOList.get(0).getShopName()).append("<BR>");
//        sb.append("商家电话: ").append(printOrderVOList.get(0).getShopTelephone()).append("<BR>");
//        sb.append("----------------------<BR>");
//        sb.append("@@2菜品明细").append("<BR>");
//
//        Double zongMoney = 0.0;
//        Double money = 0.0;
//        for (int i = 0; i < printOrderVOList.size(); i++) {
//            money = JYMathDoubleUtils.mul(printOrderVOList.get(i).getGoodsMoney(), printOrderVOList.get(i).getTotalcount());
//            zongMoney = JYMathDoubleUtils.add(zongMoney, money);   // 商品金额
//            sb.append(i + 1).append(". ").append(printOrderVOList.get(i).getGoodsName()).append("-").append(printOrderVOList.get(i).getGoodsMoney()).append("元*").append(printOrderVOList.get(i).getTotalcount()).append("份\r");
//        }
//        sb.append("----------------------<BR>");
//        sb.append("@@2支付方式").append("<BR>");
//        zongMoney = JYMathDoubleUtils.add(zongMoney, printOrderVOList.get(0).getDeliveryPrice());           // 配送费
//        //  活动满减
//        sb.append("外送费用: ").append(printOrderVOList.get(0).getDeliveryPrice()).append("元").append("<BR>");
//        sb.append("菜品金额: ").append("总价").append(zongMoney).append("元-").append("活动满减").append(printOrderVOList.get(0).getOriginalYunFeiShop()).append("元-").append("配送满减").append(printOrderVOList.get(0).getAwardMoney()).append("元").append("\r");
//        zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getAwardMoney());             //  配送满减
//        zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getOriginalYunFeiShop());
//        sb.append("应付金额: ").append(zongMoney).append("元<BR>");
//        sb.append("留言: ").append(printOrderVOList.get(0).getNote()).append("<BR>");
//
//        String content = null;   //  urlencode
//        try {
//            content = URLEncoder.encode(sb.toString(), "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//
//        boolean flag = true;
//        for (PrintMessage printMessage : list) {
//            flag = PrintMan.sendFeContent(content, printMessage.getFeUser(), printMessage.getFeUkey(), printMessage.getMachine_code(), printMessage.getFeTime());
//        }
//        //  调用打印
//        if (!flag) {
//            return AjaxResult.errorResult("打印失败,检查打印机");
//        }
//        return AjaxResult.successResult("打印成功!");
//    }

    @RequestMapping(method = RequestMethod.POST, value = "/print/fe/message")
    @ResponseBody
    public String printAction(String orderNo, String orderNos, Long shopId) {     //  订单号   打印联数
        System.out.println("手机端调用打印:orderNo->" + orderNo + ":" + orderNos + ";shopId->" + shopId);
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺id不能为空");
        }
        List<String> orderNoList = new ArrayList<>();
        if (ValidateUtil.isNotNull(orderNo)) {
            orderNoList.add(orderNo);
        }
        if (ValidateUtil.isNotNull(orderNos)) {
            List<String> list = Arrays.stream(orderNos.split(",")).collect(Collectors.toList());
            if (ValidateUtil.isAbsList(list)) {
                orderNoList.addAll(list);
            }
        }
        return PrintMan.print_message_(orderNoList, shopId, false);
    }

}
